﻿using Crm.Infrastructure.Dto.Response;
using Crm.Infrastructure.Dto.Response.Dictionary;
using Crm.Infrastructure.IOC;
using Crm.Service.Interface;
using CRM.Infrastructure.Attr;
using CRM.Infrastructure.Dto.Response;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Crm.Infrastructure.Dto.Request.Dictionary;
using CRM.Infrastructure.Tools;
using CRM.Infrastructure.EFCore.Mysql;
using CRM.Infrastructure.Dto.Response.Dictionary;
using CRM.Infrastructure.Dto.Request.Dictionary;
using CRM.Infrastructure.IOC;

namespace Crm.Service.Instance
{
    [Inject_]
    public class Dictionary_Service : Base_Service, I_Dictionary_Service
    {
        private readonly Dictionary_IOC _dictionary_IOC;
        private readonly Login_IOC _login_IOC;
        private readonly Customer_IOC _customer_IOC;
        public Dictionary_Service(Dictionary_IOC dictionary_IOC, Login_IOC login_IOC, Customer_IOC customer_IOC)
        {
            _dictionary_IOC = dictionary_IOC;
            _login_IOC = login_IOC;
            _customer_IOC = customer_IOC;
        }

        public async Task<Api_Response_Dto> Add_Dictionary(Dictionary_Request_Dto dto)
        {
            SysDictionary sysDictionary = new SysDictionary()
            {
                DId = Config.GUID_1(),
                DName = dto.name,
                DAuthor = dto.author,
                DCreateTime = DateTime.Now,
                DDesc = null,
                DUpdateAuthor = null,
                DExplain = dto.explain,
                DValue = dto.value,
                DUseCount = 0,
                DDtId = dto.dtid,
                DDiscount= dto.discount,
            };
            _dictionary_IOC._sys_Dictionary_EFCore.Add(sysDictionary);
            var result = await _dictionary_IOC._sys_Dictionary_EFCore.SaveChangesAsync();
            return Result(result);
           
        }
        /// <summary>
        /// 新增子级字典
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Add_Dictionary_type(Dictionary_Request_Dto dto)
        {
            SysDictionaryType sysDictionary = new SysDictionaryType()
            {
                DtId = Config.GUID_1(),
                DtName = dto.name,
                DtAuthor = dto.author,
                DtCreateTime = DateTime.Now,
                DtExplain = dto.explain,
                DtKey = dto.key,
                DtValue = dto.value,

            };
            _dictionary_IOC._sys_Dictionary_Type_EFCore.Add(sysDictionary);
            var result = await _dictionary_IOC._sys_Dictionary_Type_EFCore.SaveChangesAsync();
            return Result(result);
        }

        public async Task<Api_Response_Dto> Delete_Dictionarys(string id)
        {
            var count = await _customer_IOC._customer_EFCore.QueryAll(d => id == d.CType).ToListAsync();
            var count2 = 0;
            foreach (var i in count)
            {
                if (i.CType == id)
                {
                    count2 += 1;
                }
            }
            var iq = _dictionary_IOC._sys_Dictionary_EFCore.QueryAll(d => id.Contains(d.DId) && count2 == 0);
            _dictionary_IOC._sys_Dictionary_EFCore.DeleteRange(iq);
            var result = await _dictionary_IOC._sys_Dictionary_EFCore.SaveChangesAsync();
            return Result(result);
        }

        /// <summary>
        /// 删除字典类别
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Delete_Dictionary_Types(string id)
        {
            var count = await _dictionary_IOC._sys_Dictionary_EFCore.QueryAll(d => id==d.DDtId).ToListAsync();
            var count2 = 0;
                foreach (var i in count)
                {
                    if (i.DDtId == id)
                    {
                        count2 += 1;
                    }
                }
            var iq = _dictionary_IOC._sys_Dictionary_Type_EFCore.QueryAll(d => id.Contains(d.DtId) && count2 == 0);
            _dictionary_IOC._sys_Dictionary_Type_EFCore.DeleteRange(iq);
            var result = await _dictionary_IOC._sys_Dictionary_Type_EFCore.SaveChangesAsync();
            return Result(result);
        }

        /// <summary>
        /// 获取字典列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Dictionaty_Types(int page = 1, int limit = 10, string key = "")
        {
            var iq = _dictionary_IOC._sys_Dictionary_Type_EFCore.QueryAll(out int total, page, limit,
                 false, o => o.DtCreateTime, d => d.DtName!.Contains(key) || d.DtKey!.Contains(key) || d.DtValue!.Contains(key));
            
            var data = await iq.Select(d => new Dictionary_Type_Response_Dto
            {
                id = d.DtId,
                name = d.DtName,
                author = d.DtAuthor,//数据库存储的是ID 
                update_author = d.DtUpdateAuthor,//修改人ID
                explain = d.DtExplain,
                key = d.DtKey,
                time = d.DtCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                value = d.DtValue,
                count = 0,
            }).ToListAsync();

            //查询出来的数据在内存中 占用空间一般来说非常小
            var uids = data.Select(d => d.author).ToList();
            uids.AddRange(data.Select(d => d.update_author).ToList());
            var users = await _login_IOC._sys_User_EFCore.QueryAll(d => uids.Contains(d.UId)).ToListAsync();

            var count = await _dictionary_IOC._sys_Dictionary_EFCore.QueryAll(d => data.Select(e => e.id).Contains(d.DDtId)).ToListAsync();
            data.ForEach(d =>
            {
                d.author = users.Where(e => e.UId == d.author).SingleOrDefault()?.UName;
                d.update_author = users.Where(e => e.UId == d.update_author).SingleOrDefault()?.UName;
                foreach (var i in count)
                {
                    if (i.DDtId==d.id)
                    {
                        d.count += 1;
                    }
                }
                
            });

            return Result(1, "ok", new
            {
                total,
                data
            });

        }

        public async Task<Api_Response_Dto> Get_Single_Dictionary_Type(string id)
        {
            var iq = _dictionary_IOC._sys_Dictionary_Type_EFCore.QueryAll(d => d.DtId == id);
            if (!await iq.AnyAsync())
            {
                return Result(0, "参数错误");
            }
            var data = iq.Select(d => new Dictionary_Type_Response_Dto
            {
                id = d.DtId,
                name = d.DtName,
                author = d.DtAuthor,//数据库存储的是ID 
                update_author = d.DtUpdateAuthor,//修改人ID
                explain = d.DtExplain,
                key = d.DtKey,
                time = d.DtCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                value = d.DtValue,
                count = d.DtCount,
            }).Single();

            // var users=await _login_IOC._sys_User_EFCore.QueryAll(d=>d.UId==data.author || d.UId==data.update_author).ToListAsync();


            var children = await _dictionary_IOC._sys_Dictionary_EFCore.QueryAll(d => d.DDtId == id)
                .Select(d => new Dictionary_Response_Dto
                {
                    id = d.DId,
                    name = d.DName,
                    author = d.DAuthor,
                    update_author = d.DUpdateAuthor.ToString(),
                    explain = d.DExplain,
                    time = d.DCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    value = d.DValue,
                    useCount = 0
                }).ToListAsync();

            var uids = children.Select(d => d.author).ToList();
            uids.AddRange(children.Select(d => d.update_author).ToList());
            uids.Add(data.author);
            uids.Add(data.update_author);
            var users = await _login_IOC._sys_User_EFCore.QueryAll(d => uids.Contains(d.UId)).ToListAsync();
            var count = await _customer_IOC._customer_EFCore
                .QueryAll(d => children.Select(e=>e.id).Contains(d.CType)|| children.Select(e => e.id).Contains(d.CLevel)|| children.Select(e => e.id).Contains(d.CSource))
                .ToListAsync();
            children.ForEach(d =>
            {
                d.author = users.Where(e => e.UId == d.author).SingleOrDefault()?.UName;
                foreach (var i in count)
                {
                    if (i.CType==d.id||i.CLevel==d.id|| i.CSource == d.id)
                    {
                        d.useCount += 1;
                    }
                }
                d.update_author = users.Where(e => e.UId == d.update_author).SingleOrDefault()?.UName;
            });

            data.author = users.Where(e => e.UId == data.author).SingleOrDefault()?.UName;
            data.update_author = users.Where(e => e.UId == data.update_author).SingleOrDefault()?.UName;
            data.children = children;


            return Result(1, "ok", data);
        }

        public async Task<Api_Response_Dto> Update_Dictionarys(Dictionary_Response_Dto dto)
        {
            var iq = _dictionary_IOC._sys_Dictionary_Type_EFCore.QueryAll(d => d.DtId == dto.id).Single();
            iq.DtName = dto.name;
            iq.DtValue = dto.value;
            iq.DtKey = dto.key;
            iq.DtUpdateAuthor=dto.update_author;
            _dictionary_IOC._sys_Dictionary_Type_EFCore.Update(iq);
            var result=await _dictionary_IOC._sys_Dictionary_Type_EFCore.SaveChangesAsync();
            return Result(result);
        }
    }
}
